package com.szcinda.fitness;

import com.szcinda.fitness.dto.AppointmentDto;
import com.szcinda.fitness.persistence.Appointment;
import com.szcinda.fitness.utils.EncodeDecodeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class AppointmentServiceImpl implements AppointmentService {

    private final AppointmentRepository appointmentRepository;
    private final MemberRepository memberRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public AppointmentServiceImpl(AppointmentRepository appointmentRepository, MemberRepository memberRepository) {
        this.appointmentRepository = appointmentRepository;
        this.memberRepository = memberRepository;
        snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public List<AppointmentDto> getAppointmentByTrainee(String traineeOpenId) {
        List<Appointment> appointments = appointmentRepository.findByTraineeOpenId(traineeOpenId, LocalDate.now());
        List<AppointmentDto> dtos = new ArrayList<>();
        decodeName(appointments, dtos);
        return dtos;
    }

    private void decodeName(List<Appointment> appointments, List<AppointmentDto> dtos) {
        if (appointments != null && appointments.size() > 0) {
            appointments.forEach(item -> {
                AppointmentDto dto = new AppointmentDto();
                BeanUtils.copyProperties(item, dto);
                dto.setCoachName(EncodeDecodeUtil.decode(item.getCoachName()));
                dto.setTraineeName(EncodeDecodeUtil.decode(item.getTraineeName()));
                dtos.add(dto);
            });
        }
    }

    @Override
    public List<AppointmentDto> getAppointmentByCoach(String coachOpenId, LocalDate appointmentDate) {
        List<Appointment> appointments = appointmentRepository.findByCoachOpenIdAndAppointmentDate(coachOpenId, appointmentDate);
        List<AppointmentDto> dtos = new ArrayList<>();
        decodeName(appointments, dtos);
        return dtos;
    }

    @Override
    public void save(Appointment appointment) {
        appointment.setId(snowFlakeFactory.nextId());
        //编码解码
        appointment.setCoachName(EncodeDecodeUtil.encode(appointment.getCoachName()));
        appointment.setTraineeName(EncodeDecodeUtil.encode(appointment.getTraineeName()));
        appointmentRepository.save(appointment);
    }

    @Override
    public boolean checkIsMember(String openId) {
        return memberRepository.findByOpenId(openId) != null;
    }
}
